package com.xdhl.fu.fim.price.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xdhl.fu.common.core.constant.flightinfo.FlightInfoConstants;
import com.xdhl.fu.common.core.utils.MathUtils;
import com.xdhl.fu.common.core.utils.StringUtils;
import com.xdhl.fu.common.redis.service.RedisService;
import com.xdhl.fu.flight.info.api.domain.FlightInfo;
import com.xdhl.fu.flight.info.api.domain.FlightSchedule;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * 节假日价格变化策略
 *
 * @author 朱力维
 * @time 2022/6/1 20:44
 */
@Component
public class HolidaysEffectPriceStrategy implements PriceCalcStrategy {

    /**
     * 节假日折扣缓存键
     */
    public static final String CONFIG_KEY = "sys_config:holidays.discount";

    @Resource
    private RedisService redisService;

    @Override
    public int order() {
        return 1;
    }

    @Override
    public PriceCalcStrategy calcEconomy(FlightInfo flightInfo, FlightSchedule schedule) {
        String discount = redisService.getStringValue(CONFIG_KEY).split("\"")[1];
        if (StringUtils.isNotBlank(discount)) {
            Double price = MathUtils.priceMultip(Double.parseDouble(discount), schedule.getEconomyPrice());
            schedule.setEconomyPrice(price);
        }
        return this;
    }

    @Override
    public PriceCalcStrategy calcBusiness(FlightInfo flightInfo, FlightSchedule schedule) {
        String discount = redisService.getStringValue(CONFIG_KEY).split("\"")[1];
        if (StringUtils.isNotBlank(discount)) {
            Double price = MathUtils.priceMultip(Double.parseDouble(discount), schedule.getBusinessPrice());
            schedule.setBusinessPrice(price);
        }
        return this;
    }

    @Override
    public PriceCalcStrategy calcHeader(FlightInfo flightInfo, FlightSchedule schedule) {
        String discount = redisService.getStringValue(CONFIG_KEY).split("\"")[1];
        if (StringUtils.isNotBlank(discount)) {
            Double price = MathUtils.priceMultip(Double.parseDouble(discount), schedule.getHeadPrice());
            schedule.setHeadPrice(price);
        }
        return this;
    }

    @Override
    public boolean enable(FlightInfo flightInfo, FlightSchedule schedule) {
        // 判断航班的出发日期是否属于节假日
        String holidaysJSONStr = redisService.getStringValue(String.format("%s-%d", FlightInfoConstants.HOLIDAYS_KEY_PREFIX, LocalDate.now().getYear()));
        JSONObject holidaysJSON = JSONObject.parseObject(holidaysJSONStr);
        JSONArray holidays = holidaysJSON.getJSONArray(FlightInfoConstants.HOLIDAYS_KEY_PREFIX);
        for (Object holiday : holidays) {
            if (LocalDate.parse(holiday.toString()).isEqual(schedule.getStartDate())) {
                return true;
            }
        }
        return false;
    }

}
